/*
 * Code for blog.techhead.biz
 * Distributed under BSD-style license
 */

package biz.techhead.qbpos;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.CharBuffer;

/**
 *
 * @author jonathan
 */
public class RequestProcessorHTTPImpl implements RequestProcessor {
    
    private String uri = "http://localhost:8080/JWG/qbposXMLRP";
        
    public void setURI(String uri) { this.uri = uri; }

    public <T extends ResponseProcessor> T processRequest(String qbposXML, T rp) {
        try {
            String responseXML = postRequest(qbposXML);
            rp.processResponse(responseXML);
            return rp;
        } catch (IOException e) {
            throw new QBPOSException(e.getMessage(), e);
        }
    }

    private String postRequest(String qbposXML) throws IOException {

        URL url = new URL(uri);
                
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/qbpos+xml");
        con.setRequestProperty("Content-Length", String.valueOf(qbposXML.length()));

        Writer out = new OutputStreamWriter(con.getOutputStream(), "utf-8");
        try {
            out.write(qbposXML);
            out.flush();
        } finally {
            out.close();
        }
        
        Reader in = new InputStreamReader(con.getInputStream(), "utf-8");
        try {
            StringBuffer sb = new StringBuffer(2*1024);
            CharBuffer cb = CharBuffer.allocate(2*1024);
            while (in.read(cb) != -1) {
                sb.append(cb.flip());
                cb.rewind();
            }
            return sb.toString();
        } finally {
            in.close();
        }
    }
}
